package com.lzs.adx.web.modules.adx.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.constant.Constant;
import com.lzs.adx.commmon.page.PageData;
import com.lzs.adx.commmon.utils.Result;
import com.lzs.adx.commmon.validator.AssertUtils;
import com.lzs.adx.commmon.validator.ValidatorUtils;
import com.lzs.adx.commmon.validator.group.AddGroup;
import com.lzs.adx.commmon.validator.group.DefaultGroup;
import com.lzs.adx.commmon.validator.group.UpdateGroup;
import com.lzs.adx.web.commmon.annotation.LogOperation;
import com.lzs.adx.web.commmon.enums.ProductChannelConstant;
import com.lzs.adx.web.commmon.utils.ExcelUtils;
import com.lzs.adx.web.modules.adx.dto.*;
import com.lzs.adx.web.modules.adx.entity.OcpxAccountEntity;
import com.lzs.adx.web.modules.adx.excel.OcpxAccountExcel;
import com.lzs.adx.web.modules.adx.service.MonitorTemplateService;
import com.lzs.adx.web.modules.adx.service.OcpxAccountService;
import com.lzs.adx.web.modules.adx.service.OcpxConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 *
 * @author wangzhijun 825400558@qq.com
 * @since 1.0.0 2024-10-03
 */
@RestController
@RequestMapping("adx/ocpxaccount")
@Api(tags="")
public class OcpxAccountController {
    @Autowired
    private OcpxAccountService ocpxAccountService;

    @Autowired
    private OcpxConfigService ocpxConfigService;

    @Autowired
    private MonitorTemplateService monitorTemplateService;

    public static final String baseUrl="https://lhpapi.weijingrui.com/common/ocpxdb";

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("adx:ocpxaccount:page")
    public Result<PageData<OcpxAccountDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<OcpxAccountDTO> page = ocpxAccountService.page(params);

        return new Result<PageData<OcpxAccountDTO>>().ok(page);
    }


    @GetMapping("urlInfo")
    @ApiOperation("信息")
    public Result<String> getUrlInfo( String id){
        OcpxAccountEntity detail = ocpxAccountService.getDetail(id);

        MonitorTemplateDTO detail1 = monitorTemplateService.getDetail(detail.getMediaChannel());
        String clickUrl = String.format( detail1.getClickUrl(), detail.getId());

        return new Result<String>().ok(clickUrl);
    }




    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("adx:ocpxaccount:info")
    public Result<OcpxAccountDTO> get(@PathVariable("id") String id){
        OcpxAccountEntity detail = ocpxAccountService.getDetail(id);

        OcpxAccountDTO ocpxAccountDTO=new OcpxAccountDTO();
        BeanUtils.copyProperties(detail,ocpxAccountDTO);
        if(StringUtils.isNotBlank(detail.getTypeList())){
            ocpxAccountDTO.setTypeLists(JSONObject.parseArray(ocpxAccountDTO.getTypeList(), CallTypeMappingDTO.class));
        }

        return new Result<OcpxAccountDTO>().ok(ocpxAccountDTO);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("adx:ocpxaccount:save")
    public Result save(@RequestBody OcpxAccountDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        if(StringUtils.isNotBlank(dto.getIdKey())){
            dto.setId(dto.getIdKey());
        }
        //当广告位ID不为空的时候，主键就位广告位ID
        if(StringUtils.isNotBlank(dto.getTagId())){
            if(!dto.getProductChannel().equals(ProductChannelConstant.TBUNION)) {
                dto.setId(dto.getTagId());
            }
        }

        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        if(CollectionUtil.isNotEmpty(dto.getTypeLists())){
            dto.setTypeList(JSONObject.toJSONString(dto.getTypeLists()));
        }
        //关于地址的处理
        if(StringUtils.isNotBlank(dto.getReportUrl())) {
            String dspReportUrl = StringEscapeUtils.unescapeHtml4(dto.getReportUrl());
            dto.setReportUrl(dspReportUrl);
        }

        ocpxAccountService.save(dto);

        String s = HttpUtil.get(baseUrl);
        System.out.println(s);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("adx:ocpxaccount:update")
    public Result update(@RequestBody OcpxAccountDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setUpdateTime(new Date());

        if(CollectionUtil.isNotEmpty(dto.getTypeLists())){
            dto.setTypeList(JSONObject.toJSONString(dto.getTypeLists()));
        }

        if(StringUtils.isNotBlank(dto.getReportUrl())) {
            String reportUrl = StringEscapeUtils.unescapeHtml4(dto.getReportUrl());
            dto.setReportUrl(reportUrl);
        }
        //
        if(StringUtils.isNotBlank(dto.getIdKey())){
            //淘宝联盟不需要替换
            if(!dto.getProductChannel().equals(ProductChannelConstant.TBUNION)) {
                dto.setId(dto.getIdKey());
            }
        }


        ocpxAccountService.update(dto);

        String s = HttpUtil.get(baseUrl);
        System.out.println(s);

        return new Result();
    }


    @GetMapping("copy")
    public Result copy(String id){
        OcpxAccountEntity detail = ocpxAccountService.getDetail(id);
        detail.setId(null);
        detail.setCreateTime(new Date());
        detail.setUpdateTime(new Date());
        ocpxAccountService.insert(detail);
        return new Result().ok();
    }


    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("adx:ocpxaccount:delete")
    public Result delete(@RequestBody String[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        ocpxAccountService.deleteBatch(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("adx:ocpxaccount:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<OcpxAccountDTO> list = ocpxAccountService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, OcpxAccountExcel.class);
    }

}